package cn.sc.allinpay.allfavour.business.setsettle;

import android.os.Handler;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.pai.common.utils.AmtUtils;
import cn.pai.mvp.callback.MpCallBack;
import cn.sc.allinpay.allfavour.base.Utils.ListUtils;
import cn.sc.allinpay.allfavour.base.Utils.ListUtilsHook;
import cn.sc.allinpay.allfavour.base.db.DbDao;
import cn.sc.allinpay.allfavour.base.model.BaseModel;
import cn.sc.allinpay.allfavour.business.common.data.OrderData;
import cn.sc.allinpay.allfavour.business.common.data.PosData;
import cn.sc.allinpay.allfavour.business.common.data.SettleData;
import cn.sc.allinpay.allfavour.business.common.data.SettleResult;
import cn.sc.allinpay.allfavour.business.common.data.TransRecord;

/**
 * 结算
 * author：pany
 * on 2017/12/5 14:44
 */
public class SetSettleModel extends BaseModel {

    private Handler handler;

    public SetSettleModel() {
        this.handler = new Handler();
    }

    /**
     * 结算
     */
    public void querySettlement(final MpCallBack<SettleResult, String> mpCallBack) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                DbDao<TransRecord> dbDao = getDao(TransRecord.class);
                QueryBuilder<TransRecord, Integer> queryBuilder = dbDao.queryBuilder();
//                queryBuilder.orderBy("TRANSTIME", false);
                final List<SettleData> settleDataList = new ArrayList<>();
                List<TransRecord> recordList = new ArrayList<>();
                List<TransRecord> fullRecords = new ArrayList<>();
                try {
                    fullRecords = queryBuilder.query();
                    if (fullRecords != null && fullRecords.size() > 0) {
                         recordList = ListUtils.filter(fullRecords, new ListUtilsHook<TransRecord>() {
                            @Override
                            public boolean filter(TransRecord transRecord) {
                                return transRecord.getState() == 2 || transRecord.getState() == 4 || transRecord.getSellState() == 3 || transRecord.getSellState() == 4;
                                //支付状态  0：无支付状态 1:支付中 2:支付成功(全单支付完成) 3:撤销中(尚有其他子订单尚未撤销成功的) 4:撤销成功(全单撤销完成)
                            }
                        });
                    }
                    Map<String, List<TransRecord>> oilMap = new HashMap<>();
                    String[] oilArr = {"0#", "92#","95#", "98#", "LNG", "CNG", "非油品", "其它"};
                    for (String oilName: oilArr) {
                        oilMap.put(oilName, new ArrayList<TransRecord>());
                    }
                    for (TransRecord transRecord : recordList) {
                       OrderData orderData = JSON.parseObject(transRecord.getOrderData(), OrderData.class);
                       List<TransRecord> records = oilMap.get(orderData.getOilName());
                        records.add(transRecord);
                    }
                    for (String oilName: oilArr) {
                        SettleData settleData = new SettleData();
                        settleData.setOilName(oilName);
                        List<TransRecord> oilRecords = oilMap.get(oilName);
                        if (oilRecords != null && !oilRecords.isEmpty()) {
                            settleData.setSaleNum(oilRecords.size());//总交易笔数
                            for (int i = 0; i < oilRecords.size(); i++) {
                                TransRecord record = oilRecords.get(i);
                                countSale(settleData, record);
                                countDed(settleData, record);
                                countPos(settleData, record);
                                countVoid(settleData, record);
                                settleData.setPadiAmt(settleData.getSaleAmt().subtract(settleData.getVoidAmt()));

                            }
                        }
                        settleDataList.add(settleData);
                    }
                } catch (final SQLException e) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            mpCallBack.onFailure(null, e.getMessage());
                        }
                    });
                }
                final List<TransRecord> finalRecordList = recordList;
                final List<TransRecord> finalFullRecords = fullRecords;
                final List<TransRecord> finalRecordList1 = recordList;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        SettleResult settleResult = new SettleResult();

                        settleResult.setSettleDataList(settleDataList);

                        if (finalFullRecords != null && finalFullRecords.size() > 0) {
                            Collections.sort(finalFullRecords, new Comparator<TransRecord>() {
                                @Override
                                public int compare(TransRecord o1, TransRecord o2) {
                                    String date1 = o1.getTransDate() + o1.getTransTime();
                                    String date2 = o2.getTransDate() + o2.getTransTime();
                                    return (int) (Long.parseLong(date1) - Long.parseLong(date2));
                                }
                            });

                        }

                        Date myDate1 = new Date();
                        Date myDate2 = new Date();

                        if (finalFullRecords.size() > 0) {
                            TransRecord record1 =  finalFullRecords.get(0);
                            DateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
                            try {
                                myDate1 = dateFormat1.parse(record1.getTransDate() + record1.getTransTime());
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }

                        DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        settleResult.setTvSettleTime(dateFormat2.format(myDate1));
                        settleResult.setTvSettleTime2(dateFormat2.format(myDate2));

                        settleResult.setTvSaleNum(finalRecordList1.size() + "笔");

                        BigDecimal saleAmt = BigDecimal.ZERO;
                        BigDecimal voidAmt = BigDecimal.ZERO;
                        BigDecimal paidAmt = BigDecimal.ZERO;
                        BigDecimal memberDisAmt = BigDecimal.ZERO;
                        BigDecimal couponAmt = BigDecimal.ZERO;
                        BigDecimal walletAmt = BigDecimal.ZERO;
                        BigDecimal cashAmt = BigDecimal.ZERO;
                        BigDecimal onlineAmt = BigDecimal.ZERO;
                        int voidNum = 0;

                        for (SettleData settleData : settleDataList) {
                            if (!TextUtils.isEmpty(settleData.getSaleAmt().toString())) {
                                saleAmt = saleAmt.add(settleData.getSaleAmt());
                            }
                            if (!TextUtils.isEmpty(settleData.getVoidAmt().toString())) {
                                voidAmt = voidAmt.add(settleData.getVoidAmt());
                               voidNum = voidNum + settleData.getVoidNum();
                            }

                            if (!TextUtils.isEmpty(settleData.getPadiAmt().toString())) {
                                paidAmt = paidAmt.add(settleData.getPadiAmt());

                            }

                            if (!TextUtils.isEmpty(settleData.getMemberDisAmt().toString())) {
                                memberDisAmt = memberDisAmt.add(settleData.getMemberDisAmt());
                            }

                            if (!TextUtils.isEmpty(settleData.getCouponAmt().toString())) {
                                couponAmt = couponAmt.add(settleData.getCouponAmt());
                            }

                            if (!TextUtils.isEmpty(settleData.getWalletAmt().toString())) {
                                walletAmt = walletAmt.add(settleData.getWalletAmt());
                            }

                            if (!TextUtils.isEmpty(settleData.getCashAmt().toString())) {
                                cashAmt = cashAmt.add(settleData.getCashAmt());
                            }

                            if (!TextUtils.isEmpty(settleData.getOnlineAmt().toString())) {
                                onlineAmt = onlineAmt.add(settleData.getOnlineAmt());
                            }
                        }

                        settleResult.setTvSale( AmtUtils.formatY(saleAmt));
                        settleResult.setTvVoid( AmtUtils.formatY(voidAmt));
                        settleResult.setTvVoidNum(voidNum + "笔");
                        settleResult.setTvPaid( AmtUtils.formatY(paidAmt));
                        settleResult.setTvMemberDis( AmtUtils.formatY(memberDisAmt));
                        settleResult.setTvCoupon( AmtUtils.formatY(couponAmt));
                        settleResult.setTvWallet( AmtUtils.formatY(walletAmt));
                        settleResult.setTvCash( AmtUtils.formatY(cashAmt));
                        settleResult.setTvOnline( AmtUtils.formatY(onlineAmt));

                        mpCallBack.onSuccess(settleResult);
                    }
                });
            }
        }).start();
    }

    /**
     * 计算消费总金额
     *
     * @param settleData
     * @param record
     */
    private void countSale(SettleData settleData, TransRecord record) {
        if (!TextUtils.isEmpty(record.getDisCouponAmt())) {//卡券
            BigDecimal couponAmt = new BigDecimal(record.getDisCouponAmt());
            settleData.setSaleAmt(settleData.getSaleAmt().add(couponAmt));
        }
        if (!TextUtils.isEmpty(record.getDisEWalletAmt())) {//电子钱包
            BigDecimal walletAmt = new BigDecimal(record.getDisEWalletAmt());
            settleData.setSaleAmt(settleData.getSaleAmt().add(walletAmt));
        }
        if (!TextUtils.isEmpty(record.getDisRightsAmt())) {//会员优惠
            BigDecimal disRightsAmt = new BigDecimal(record.getDisRightsAmt());

            if (record.getState() == 2 || record.getSellState() == 3) {
                settleData.setMemberDisAmt(settleData.getMemberDisAmt().add(disRightsAmt));
            }
            settleData.setSaleAmt(settleData.getSaleAmt().add(disRightsAmt));
        }
        //交易总金额即卡券，电子钱包，会员优惠，POS支付的总金额
        if (!TextUtils.isEmpty(record.getPaidAmt())) {//待支付金额，Pos支付金额
            BigDecimal paidAmt = new BigDecimal(record.getPaidAmt());
            settleData.setSaleAmt(settleData.getSaleAmt().add(paidAmt));
        }
    }

    /**
     * 计算卡券和电子钱包总金额
     *
     * @param settleData
     * @param record
     */
    private void countDed(SettleData settleData, TransRecord record) {
        //部分抵扣成功和全额抵扣成功
        if (record.getSellState() == 1 || record.getSellState() == 3) {
            if (!TextUtils.isEmpty(record.getDisCouponAmt())) {//卡券
                BigDecimal couponAmt = new BigDecimal(record.getDisCouponAmt());
                settleData.setCouponAmt(settleData.getCouponAmt().add(couponAmt));
            }
            if (!TextUtils.isEmpty(record.getDisEWalletAmt())) {//电子钱包
                BigDecimal walletAmt = new BigDecimal(record.getDisEWalletAmt());
                settleData.setWalletAmt(settleData.getWalletAmt().add(walletAmt));
            }

        }
    }

    /**
     * 计算POS实际支付的金额
     *
     * @param settleData
     * @param record
     */
    private void countPos(SettleData settleData, TransRecord record) {
        //支付成功和撤销中。注:因为先撤销的抵扣，再撤销的POS
        if ((record.getState() == 2 || record.getState() == 3) && !TextUtils.isEmpty(record.getPosData())) {
            PosData posData = JSON.parseObject(record.getPosData(), PosData.class);
            if (!TextUtils.isEmpty(posData.getCashAmt())) {//现金
                BigDecimal cashAmt = new BigDecimal(posData.getCashAmt());
                settleData.setCashAmt(settleData.getCashAmt().add(cashAmt));
            }
//            if ("消费".equals(posData.getTransType())) {
//                BigDecimal cardAmt = new BigDecimal(posData.getAmount());
//                settleData.setCardAmt(settleData.getCardAmt().add(cardAmt));
//            } else if ("支付宝支付".equals(posData.getTransType())) {
//                BigDecimal aliAmt = new BigDecimal(posData.getAmount());
//                settleData.setAliAmt(settleData.getAliAmt().add(aliAmt));
//            } else if ("微信支付".equals(posData.getTransType())) {
//                BigDecimal wxAmt = new BigDecimal(posData.getAmount());
//                settleData.setWxAmt(settleData.getWxAmt().add(wxAmt));
//            }
            if (!TextUtils.isEmpty(posData.getAmount())) {//非现金
                BigDecimal onlineAmt = new BigDecimal(posData.getAmount());

                settleData.setOnlineAmt(settleData.getOnlineAmt().add(onlineAmt));
            }

        }
    }

    /**
     * 计算撤销金额
     *
     * @param settleData
     * @param record
     */
    private void countVoid(SettleData settleData, TransRecord record) {
        //pos撤销成功或者部分抵扣撤销或者全额抵扣撤销
        boolean isVoid = false;
        if (record.getSellState() == 2 || record.getSellState() == 4) {
            isVoid = true;
            if (!TextUtils.isEmpty(record.getDisCouponAmt())) {
                settleData.setVoidAmt(settleData.getVoidAmt().add(new BigDecimal(record.getDisCouponAmt())));
            }
            if (!TextUtils.isEmpty(record.getDisEWalletAmt())) {
                settleData.setVoidAmt(settleData.getVoidAmt().add(new BigDecimal(record.getDisEWalletAmt())));
            }

            if (!TextUtils.isEmpty(record.getDisRightsAmt())) {
                settleData.setVoidAmt(settleData.getVoidAmt().add(new BigDecimal(record.getDisRightsAmt())));
            }
        }
        if (record.getState() == 4 && !TextUtils.isEmpty(record.getPaidAmt())) {
            isVoid = true;
            settleData.setVoidAmt(settleData.getVoidAmt().add(new BigDecimal(record.getPaidAmt())));
        }
        if(isVoid) {
            settleData.setVoidNum((settleData.getVoidNum() + 1));
        }
    }

    /**
     * 删除交易流水数据
     */
    public void delTransRecord(final MpCallBack<Integer, String> mpCallBack) {
        DbDao<TransRecord> dbDao = new DbDao<>(TransRecord.class);
        DeleteBuilder<TransRecord, Integer> deleteBuilder = dbDao.deleteBuilder();
        try {
            int result = deleteBuilder.delete();
            mpCallBack.onSuccess(result);
        } catch (SQLException e) {
            mpCallBack.onFailure(null, e.getMessage());
        }
    }
}
